package org.ch02.test00.demo06.myWork;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * SQL生成对象
 * @author CSY
 * @date 2025 - 03 - 18
 */
public class SqlGenerate {
    public static StringBuilder generateSelect(Class<?> clz){
        Field[] declaredFields = clz.getDeclaredFields();
        StringBuilder sql = new StringBuilder();
        sql.append("select ");
        for (Field f : declaredFields){
            sql.append(convert(f.getName()).toLowerCase()+" as "+f.getName()+",");
        }
        sql =  new StringBuilder(sql.substring(0,sql.length()-1));

        sql.append(" from ");

        String simpleName = clz.getSimpleName();

        sql.append(convert(simpleName));
        return sql;
    }

    public static String generateSelect(Class<?> clz, Map<String,Object> cond){
        //调用重载方法，获取查询所有字段的SQL语句
        StringBuilder sql = new StringBuilder(generateSelect(clz));

        if (cond == null && cond.size() == 0){
            return sql.toString();
        }
        sql.append(" where ");
        for (String k : cond.keySet()) {
            sql.append(k).append("= ?").append(" and ");
        }
        ;

        return sql.substring(0,sql.length() - 5);
    }

    /**
     * 转换
     * @return 转换后的字符
     */
    public static String convert(String msg){
        StringBuilder fields = new StringBuilder(String.valueOf(msg.charAt(0)));
        for (int i = 1;i < msg.length();i++){
            if(Character.isUpperCase(msg.charAt(i))){
                fields.append("_" + msg.charAt(i));
                continue;
            }
            fields.append(msg.charAt(i));
        }
        return fields.toString().toLowerCase();
    }
}
